#!/usr/bin/perl

# $Id: 02_ftpwrapper.t 136 2010-06-26 14:47:28Z dolbanavt $
# $Date: 2010-06-26 17:47:33 +0300 (Суб, 26 Июн 2010) $
# $HeadURL: https://robosearch.googlecode.com/svn/branches/reborn/t/02_ftpwrapper.t $
# $LastChangedRevision: 349 $

use FindBin qw( $RealBin );
use File::Spec::Functions qw( catfile );

BEGIN {
    push @INC, catfile( $RealBin, '..', 'base_lib' );
    push @INC, catfile( $RealBin, '..', 'lib' );
}

use JIP::ToolSet;
use English qw( -no_match_vars );
use Test::More 0.88;
use Const::Fast qw( const );
use Test::MockObject;
use Test::Exception;

const my $MODULE => 'FTPWrapper';

use_ok $MODULE;
require_ok $MODULE;

can_ok $MODULE, qw(
    new _init
    set_connection get_connection
    set_listing_decorator get_listing_decorator
    get_listing_for
);

throws_ok { $MODULE->new(); }
    qr{^Required\soption\s'connection'\sis\snot\sprovided}xms,
    'new( connection )';

throws_ok { $MODULE->new( connection => q{} ); }
    qr{^Required\soption\s'decorator'\sis\snot\sprovided}xms,
    'new( decorator )';

{
    my $mock = Test::MockObject->new();

    $mock->fake_module( 'FTPListing::Unix',
        new     => sub {
            return bless {}, 'FTPListing::Unix'
        },
        parse_listing_for => sub {
            my ( $self, $path ) = @ARG;

            is ref $self,
               'FTPListing::Unix',
               'its mock FTPListing::Unix::parse_listing_for()';

            is $path,
               'path_to_dir',
               'FTPListing::Unix::parse_listing_for(path)';

            return ( { name => 'filename', type => 'f', size => 128 } );
        },
    );

    $mock->fake_module( 'Net::FTP',
        new => sub {
            return bless {}, 'Net::FTP'
        },
        dir => sub {
            my ( $self, $path ) = @ARG;

            is ref $self,
               'Net::FTP',
               'its mock Net::FTP::dir()';

            is $path,
               'path_to_dir',
               'Net::FTP::dir(path)';

            return $path;
        },
    );

    my $w = $MODULE->new(
        connection => Net::FTP->new(),
        decorator  => FTPListing::Unix->new(),
    );

    ok $w, 'got object';

    isa_ok $w, $MODULE;
    isa_ok $w, 'JIP::BaseClass';
    isa_ok $w, 'Class::Accessor::Fast';

    is ref $w->get_connection,
       'Net::FTP',
       'connection accessor';

    is ref $w->get_listing_decorator,
       'FTPListing::Unix',
       'listing_decorator accessor';

    my @l = $w->get_listing_for('path_to_dir');

    is scalar @l, 1, 'get_listing_for() returned one record';

    is $l[0]->{'name'}, 'filename', 'file - record name';
    is $l[0]->{'type'}, 'f',        'file - record type';
    is $l[0]->{'size'}, '128',      'file - record size';
}

done_testing();
